<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/7/11
 * Time: 15:43
 */

namespace common\components\image\driver;

use \Imagick;
use yii\base\Exception;
use common\components\image;

class ImageMagic
{
    /**
     * @var Imagick
     */
    public $imageMagic;
    //public $tmpArray;
    //public $imageScaleList=[]; //缩放的图片
    public $scalImage; //图片组合列表
    public $width;  // 图片宽
    public $height; // 图片高
    public $x;//裁剪的 x轴位置
    public $y;//裁剪的 y轴位置
    public $xh; //裁剪图片的标识  1 横向切  2 纵向切
    public $imageArray;
    /**
     * @var Imagick
     */
    public $combination;//创建一个新的画布
    public $pos_x; //组合位置 x
    public $pos_y; // 组合位置 y
    public $templateArray; //模版数据数组
    public $aspect; // 组合图片排列规则 是 横向排列 还是纵向排列
    public $new_width; // 记录每次相加后的 新的宽度
    public $new_height; // 记录每次相加后的 新的高度
    public $temp_width; //临时宽 用完清0
    public $temp_height; //临时高  用完清0
    public $leftDistance = 10; // 小图 距离大图的左边距离 和 离顶部的边距
    public $marginsDistance =10; //小图直接的不边距
    public function __construct()
    {
        if (empty($this->imageMagic)) {
            $this->imageMagic = new Imagick();
        }

        //return $this->imageMagic;

    }

    /** 生成缩略图
     * @param $file
     * @param array $thumb
     * @return array
     */
    public function createThumb($file, $thumb)
    {
        if (empty($thumb) || empty($file)) {
            return false;
        }
        $fileName = [];
        //print_r($file);exit;
        $this->imageMagic->readImage($file['absolutePath']);
        foreach ($thumb as $key => $val) {
            $this->imageMagic->cropThumbnailImage($val[0], $val[1]);
            $this->imageMagic->writeImage($file['basePath'] . $file['path'] . DIRECTORY_SEPARATOR . $file['shortName'] . '_' . $key . '.' . $file['extension']);
            $fileName[$file['shortName'] . '_' . $key . '.' . $file['extension']] = $file['basePath'] . $file['path'] . DIRECTORY_SEPARATOR . $file['shortName'] . '_' . $key . '.' . $file['extension'];
        }
        $this->destory();
        return $fileName;
    }
    public function createThumbImage($file, $thumb)
    {
        if (empty($thumb) || empty($file)) {
            return false;
        }
        $fileName = [];
        //print_r($file);exit;
        $path=pathinfo($file);
        $name=substr($path['basename'],0,strpos($path['basename'],'.'));
        $this->imageMagic->readImage($file);
            $this->imageMagic->cropThumbnailImage($thumb[0], $thumb[1]);
            $this->imageMagic->writeImage($path['dirname'] . DIRECTORY_SEPARATOR . $name . '_0.' . $path['extension']);
            $fileName[$name . '_0.' . $path['extension']] = $path['dirname'] . DIRECTORY_SEPARATOR . $name . '_0.' . $path['extension'];

        $this->destory();
        return $fileName;
    }
    /**
     * 裁剪图片
     * @param string $imagePath
     * @param int $width
     * @param int $height
     * @return  array
     */
    public function cropImage($imagePath, $width, $height)
    {
        $this->getImageInfo($imagePath); //extension  dirname basename
        $this->imageMagic->readImage($imagePath);
        $geometry = $this->imageMagic->getImageGeometry();
        $this->width = $width;
        $this->height = $height;
        $w = 0;
        $h = 0;
        //根据图片的宽*高 缩放图片
        if ($geometry['width'] < $geometry['height']) {
            $w = $width;
            $h = intval(($width / $geometry['width']) * $geometry['height']);
            $this->xh = 2;
        }
        if ($geometry['width'] > $geometry['height']) {
            $w = intval(($height / $geometry['height']) * $geometry['width']);
            $h = $height;
            $this->xh = 1;
        }
        //处理特殊情况 图片是正方形的时候
        if($geometry['width'] == $geometry['height']){
            if($this->width >= $this->height){
                $w=$this->width;
                $h=$this->width;
                $this->xh=1;
            }
            if($this->width < $this->height){
                $w=$this->height;
                $h=$this->height;
                $this->xh=2;
            }
        }
        $this->imageMagic->cropThumbnailImage($w, $h);
        if ($this->xh == 2) {
            $this->x = 0;
            $this->y = intval(($h - $height) / 2);
        }
        if ($this->xh == 1) {
            $this->x = intval(($w - $width) / 2);
            $this->y = 0;
        }
        $this->imageMagic->cropImage($this->width, $this->height, $this->x, $this->y);
        //$this->combination->
        //$this->imageMagic->writeImage($this->imageArray['dirname'].DIRECTORY_SEPARATOR.$this->imageArray['name'].'_1.'.$this->imageArray['type']);
        //$this->destory();
        //$imagic->imageMagic->writeImage($this->imageArray['dirname'].DIRECTORY_SEPARATOR.$this->imageArray['name']);
    }

    /**
     * 新建画布
     * @param $width
     * @param $height
     * @param string $backGroud
     * @param string $format
     */
    public function ImagGicInit($width, $height, $backGroud = 'white', $format = 'jpg', $aspect)
    {
        if (empty($this->combination)) {
            $this->combination = new Imagick();
        }
        $this->combination->newImage($width, $height, $backGroud);
        $this->combination->setImageFormat($format);
        $this->aspect = $aspect;
        $this->new_width = $width;
        $this->new_height = $height;
    }

    /**
     * 图片组合
     * @param $imageData
     * @return bool
     */
    public function combinationImage($imageData)
    {
        if (empty($imageData)) {
            return false;
        }
        //$basePath = \Yii::$app->basePath.DIRECTORY_SEPARATOR.'web/uploads'.DIRECTORY_SEPARATOR;
        $i = 0;
        foreach ($imageData as $key => $val) {
            $this->cropImage($key,$val[0],$val[1]);
            //横向排版
            if ($this->aspect == 1) {

                if ($i == 0) {
                    if ($val[0] < $this->new_width) {
                        $this->pos_x=$this->leftDistance;
                        $this->pos_y=$this->leftDistance;
                        $this->temp_width = $this->leftDistance + $this->width ;
                        $this->temp_height =  $this->leftDistance;
                        //$i=$i+1;
                       // $this->combination->compositeImage($this->imageMagic, Imagick::COMPOSITE_OVER, $this->pos_x, $this->pos_y);
                    }
                }
                //echo $i;echo $this->pos_x;exit;
                if($i > 0){
                    //echo intval($this->new_width - $this->temp_width);exit;
                    if(intval($this->new_width - $this->temp_width) > $val[0]) {
                        $this->pos_x=$this->temp_width + $this->leftDistance;
                        $this->pos_y=$this->pos_y;
                        $this->temp_width=$this->temp_width + $this->width+ $this->leftDistance;
                        //设置一个阀值  更具阀值判断是否要初始化 临时的宽高记录值
                        if(intval($this->new_width - $this->temp_width) > $val[0]){
                            $this->temp_height=$this->temp_height;
                        }else{
                            $this->temp_height=$this->temp_height + $this->height;
                        }

                        //$this->combination->compositeImage($this->imageMagic, Imagick::COMPOSITE_OVER, $this->pos_x, $this->pos_y);
                        //$i=$i+1;

                    }else{
                        $this->pos_x=$this->leftDistance;
                        $this->pos_y= $this->temp_height + $this->leftDistance;
                        //$this->temp_width=$this->leftDistance;
                        //这个时候需要初始化 以前的宽的值
                        $this->temp_width=$this->leftDistance + $this->width;
                        //设置一个阀值  更具阀值判断是否要初始化 临时的宽高记录值
                        if(intval($this->new_width - $this->temp_width) > $val[0]){
                            $this->temp_height=$this->temp_height;
                        }else{
                            $this->temp_height=$this->temp_height + $this->height;
                        }
                       // $this->temp_height= $this->temp_height + $this->height + $this->leftDistance;
                       // $this->combination->compositeImage($this->imageMagic, Imagick::COMPOSITE_OVER, $this->pos_x, $this->pos_y);
                        //$i=$i+1;
                    }

                }
                //$i 加 1
                $this->combination->compositeImage($this->imageMagic, Imagick::COMPOSITE_OVER, $this->pos_x, $this->pos_y);
                $i=$i+1;
            }
            //纵向排版
            if($this->aspect == 2){

            }
            //echo $this->pos_x;
            //$this->combination->compositeImage($this->imageMagic, Imagick::COMPOSITE_OVER, $this->pos_x, $this->pos_y);
        }
        $i=0;
        //$this->combination->writeImage();
    }

    /**
     * @param string $imagePath
     * @return array|bool
     */
    public function getImageInfo($imagePath)
    {
        $imageInfo = pathinfo($imagePath); //extension  dirname basename
        $length = strpos($imageInfo['basename'], '.');
        if ($length === false) {
            return false;
        }
        $imageName = substr($imageInfo['basename'], 0, $length - 1);
        $this->imageArray = ['name' => $imageName, 'type' => $imageInfo['extension'], 'dirname' => $imageInfo['dirname']];
        // return ['name'=>$imageName,'type'=>$imageInfo['extension'],'dirname'=>$imageInfo['dirname']];
    }

    /**
     * 获取图片的宽 高
     * @param $filePath
     * @return array
     */
    public function  getImageGeometry($file)
    {
        if (!empty($file)) {
            $this->imageMagic->readImage($file);
            return $this->imageMagic->getImageGeometry();
        }
        return false;
    }

    /**
     * 释放图片资源
     */
    public function destory()
    {
        if (is_object($this->imageMagic)) {
            $this->imageMagic->clear();
            $this->imageMagic->destroy();
        }
    }

    public function __destory()
    {
        if (is_object($this->imageMagic)) {
            $this->imageMagic->clear();
            $this->imageMagic->destroy();
        }
    }
}